package com.woniu.microownerserver.service.impl;

import com.alibaba.fastjson.JSON;
import com.woniu.microcommonsserver.param.ResponseMsg;
import com.woniu.microownerserver.bean.BookInfo;
import com.woniu.microownerserver.bean.SearchQuery;
import com.woniu.microownerserver.service.BookService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class BookServiceimpl implements BookService {
    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient client;

    @Override
    public ResponseMsg searchByQuery(SearchQuery searchQuery) throws IOException {
        if(searchQuery.getPageNum()<=0){
            return null;
        }
        //条件构建
        SearchRequest searchRequest = new SearchRequest();
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        TermQueryBuilder termQueryBuilder=null;

        System.out.println("默认条件");
        sourceBuilder.query(QueryBuilders.matchQuery("novel_status_msg","连载中"));
        if (searchQuery.getBookName()!=null && searchQuery.getBookName()!=""){
            System.out.println("进入书名条件");
            termQueryBuilder = QueryBuilders.termQuery("novel_name", searchQuery.getBookName());
            sourceBuilder.query(termQueryBuilder);
        }else if(searchQuery.getDesc()!=null && searchQuery.getDesc()!=""){
            System.out.println("进入描述条件");
            MatchQueryBuilder describe = QueryBuilders.matchQuery("describe", searchQuery.getDesc());
            sourceBuilder.query(describe);
        }

        sourceBuilder.timeout(new TimeValue(10, TimeUnit.SECONDS));
        //分页查找
        sourceBuilder.from(searchQuery.getPageNum()-1);
        sourceBuilder.size(searchQuery.getPageSize());
        //高亮
        HighlightBuilder builder = new HighlightBuilder();
        builder.field("describe");
        builder.preTags("<span style='color:red'>");
        builder.postTags("</span>");
        sourceBuilder.highlighter(builder);

        //执行搜索
        searchRequest.source(sourceBuilder);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        System.out.println(response.getHits().getTotalHits());//total
        //解析结果
        ArrayList<BookInfo> list = new ArrayList();
        for (SearchHit hit : response.getHits().getHits()) {
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField describe = highlightFields.get("describe");
            Map<String, Object> map1 = hit.getSourceAsMap();//原来的结果
            if (describe!=null){
                Text[] texts = describe.fragments();
                String newdesc="";
                for (Text text : texts) {
                    newdesc+=text;
                }
                map1.put("describe",newdesc);//替换
                String s = JSON.toJSONString(map1);
                BookInfo bookInfo = JSON.parseObject(s, BookInfo.class);
                list.add(bookInfo);
            }else{
            Map<String, Object> map = hit.getSourceAsMap();
            System.out.println(map);
            //将map转为json
            String s = JSON.toJSONString(map);
            //转为对象
            BookInfo bookInfo = JSON.parseObject(s, BookInfo.class);
            list.add(bookInfo);
            }

        }
        return ResponseMsg.builder().code((int)response.getHits().getTotalHits().value).msg("asd").data(list).build();
    }
}
